package com.mypack.student.service.achievement.impl;

import com.github.pagehelper.PageHelper;
import com.mypack.student.constants.EnumDeleteFlag;
import com.mypack.student.dto.achievement.StudentAchievementDTO;
import com.mypack.student.dto.achievement.StudentAchievementSearchDTO;
import com.mypack.student.entity.EduStudentAchievement;
import com.mypack.student.mapper.StudentAchievementMapper;
import com.mypack.student.service.achievement.StudentAchievementService;
import ma.glasnost.orika.MapperFacade;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
@Transactional
public class StudentAchievementServiceImpl implements StudentAchievementService {

    @Autowired
    private StudentAchievementMapper studentAchievementMapper;
    @Autowired
    private MapperFacade mapperFacade;

    @Override
    public List<StudentAchievementDTO> list(StudentAchievementSearchDTO searchDTO, boolean isPage) {

        if (StringUtils.isEmpty(searchDTO.getSortField()) || StringUtils.isEmpty(searchDTO.getSortType())) {
            searchDTO.setSortField("id");
            searchDTO.setSortType("desc");
        }

        if (isPage) {
            PageHelper.startPage(searchDTO.getPageNum(), searchDTO.getPageSize(), searchDTO.getSortField() + " " + searchDTO.getSortType());
        }

        return studentAchievementMapper.list(searchDTO);
    }

    @Override
    public void add(StudentAchievementDTO studentAchievementDTO) {

        studentAchievementDTO.setCreateTime(new Date());
        studentAchievementDTO.setUpdateTime(new Date());
        studentAchievementDTO.setDeleteFlag(EnumDeleteFlag.NO.getCode());

        EduStudentAchievement eduStudentAchievement = mapperFacade.map(studentAchievementDTO, EduStudentAchievement.class);

        studentAchievementMapper.insert(eduStudentAchievement);
    }

    @Override
    public void update(StudentAchievementDTO studentAchievementDTO) {

        if (studentAchievementDTO.getId() == null) {
            return;
        }

        EduStudentAchievement eduStudentAchievement = mapperFacade.map(studentAchievementDTO, EduStudentAchievement.class);

        studentAchievementMapper.updateById(eduStudentAchievement);
    }
}
